import inspect
import sys
import os
from utils.log import setup_my_logging
import traceback

from utils.Command import BaseCommand

if __name__ == "__main__":
    def is_basecommand_subclass(value):
        if inspect.isclass(value) and issubclass(value, BaseCommand) and value != BaseCommand:
            return True
        else:
            return False
    try:
        ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
        os.chdir(ROOT_DIR)
        sys.path.append(ROOT_DIR)
        setup_my_logging()
        if len(sys.argv) > 1:
            # load rule module and run rule
            command = __import__(
                "commands.{}".format(sys.argv[1]),
                fromlist=['xxx']
            )
            classes = inspect.getmembers(command, is_basecommand_subclass)
            if len(classes) > 0:
                classes[0][1]().execute(sys.argv[2:])
    except Exception as e:
        print(traceback.format_exc())
        print(e)

